#!/bin/bash
FILE_ROOT_DIR=$(cd "$(dirname ${BASH_SOURCE[0]})/../.."; pwd)
APPPLUGINS_ROOT_PATH=$(cd "${FILE_ROOT_DIR}/.."; pwd)
FRAMEWORK_DIR=$(cd "${FILE_ROOT_DIR}/../../framework"; pwd)
FS_BACKUP_DIR=$(cd "${FILE_ROOT_DIR}/../../FS_Backup"; pwd)
FRAMEWORK_OUTPUT=${FRAMEWORK_DIR}/output_pkg
MODULE_THIRD_DIR=$(cd "${FILE_ROOT_DIR}/../../Module/third_open_src"; pwd)
MODULE_THIRD_DIR_PLATFORM=$(cd "${FILE_ROOT_DIR}/../../Module/platform"; pwd)
source ${FRAMEWORK_DIR}/build/common/common.sh
SCRIPT_NAME="${BASH_SOURCE[0]##*/}"
MODULE_LIB_DIR="${FILE_ROOT_DIR}/../../Module/lib"

function copy_file()
{
    # Copy framework/lib files
    mkdir -p ${PLUGIN_PACKAGE_PATH}/lib
    cp -rf ${FRAMEWORK_DIR}/lib/* ${PLUGIN_PACKAGE_PATH}/lib

    # Copy conf files
    mkdir -p  ${PLUGIN_PACKAGE_PATH}/conf
    cp -f ${FILE_ROOT_DIR}/conf/* ${PLUGIN_PACKAGE_PATH}/conf

    # Copy bin script files
    mkdir -p  ${PLUGIN_PACKAGE_PATH}/bin
    cp -f ${FILE_ROOT_DIR}/bin/* ${PLUGIN_PACKAGE_PATH}/bin

    # Copy obs plugin library
    NAS_LIB_PATH=${FILE_ROOT_DIR}/build-cmake
    mkdir -p ${PLUGIN_PACKAGE_PATH}/lib/service
    find ${NAS_LIB_PATH} -name "*.so" | xargs -I{} cp -f {} ${PLUGIN_PACKAGE_PATH}/lib/service
    
    # Copy Module library
    find ${MODULE_LIB_DIR} -name "*.so" | xargs -I{} cp -f {} ${PLUGIN_PACKAGE_PATH}/lib/service

    # Copy Scanner library
    SCANNER_DIR=$(cd "${APPPLUGINS_ROOT_PATH}/../FS_Scanner"; pwd)
    SCANNER_LIB_PATH=${SCANNER_DIR}/lib
    find ${SCANNER_LIB_PATH} -name "*.so" | xargs -I{} cp -f {} ${PLUGIN_PACKAGE_PATH}/lib/service

    # Copy Backup library
    # BACKUP_DIR=$(cd "${APPPLUGINS_ROOT_PATH}/../FS_Backup"; pwd)
    BACKUP_LIB_PATH=${FS_BACKUP_DIR}/build-cmake
    find ${BACKUP_LIB_PATH} -name "*.so" | xargs -I{} cp -f {} ${PLUGIN_PACKAGE_PATH}/lib/service

    # Copy opensource
    OPENSRC_LIST="lnfs lsmb2 jsoncpp openssl libiconv libssh2 esdk 7z icu"
    mkdir -p ${PLUGIN_PACKAGE_PATH}/lib/3rd
    for opensrc in ${OPENSRC_LIST}; do
        find ${MODULE_THIRD_DIR}/${opensrc}_rel -name "*.so*" | xargs -I{} cp -f {} ${PLUGIN_PACKAGE_PATH}/lib/3rd
    done

    PLATFORM_LIST="ALiCloudSDK KMCv3_infra"
    for platform in ${PLATFORM_LIST}; do
        find ${MODULE_THIRD_DIR_PLATFORM}/${platform}_rel -name "*.so*" | xargs -I{} cp -f {} ${PLUGIN_PACKAGE_PATH}/lib/3rd
    done

    # copy OBS.ini
    cp -f ${FILE_ROOT_DIR}/build/install/OBS.ini.copy ${PLUGIN_PACKAGE_PATH}/lib/3rd

    # Copy script into package
    cp -f ${FILE_ROOT_DIR}/build/install/start.sh ${PLUGIN_PACKAGE_PATH}/
}

function main()
{
    # build plugin
    #sh ${FILE_ROOT_DIR}/CI/script/build.sh $@
    if [ $? -ne 0 ]; then
        log_echo "ERROR" "Building obs lib failed"
        exit 1
    fi

    # build obs plugin
    copy_file

    # Execute framework package
    sh ${FRAMEWORK_DIR}/build/pack.sh
}

main "$@"
